<template>
  <el-card body-style="min-height: 86vh">
    <!-- 新增、筛选按钮 -->
    <div class="flex justify-between">
      <div>
        <el-button type="primary" @click="handleCreate()">新增</el-button>
      </div>
      <div>
        <el-button circle @click="handleGetTableList()">
          <template #icon
            ><el-icon> <Refresh /> </el-icon
          ></template>
        </el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData">
      <el-table-column label="角色" prop="roleName" align="center"></el-table-column>
      <el-table-column label="描述" prop="remark" align="center"></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'primary' : 'danger'">{{
            row.status ? "正常" : "停用"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button v-if="row.isAdmin === 0" type="primary" @click="handleConfigPermission(row)"
            >菜单权限</el-button
          >
          <el-button type="primary" @click="handleEdit(row)">修改</el-button>
          
          <el-popconfirm
            v-if="row.isAdmin === 0"
            width="180"
            title="是否要删除该角色？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex justify-center mt-2"
      background
      layout="total,prev, pager, next"
      :current-page="currentPage"
      :page-size="limit"
      :total="total"
      @current-change="handleGetTableList"
    />
    <!-- 配置权限 -->
    <form-drawer ref="formDrawerRefRule" title="配置权限" @submit="handleSubmitConfigPermission">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        node-key="id"
        :data="curMunuList"
        show-checkbox
        :check-strictly="true"
        :default-expanded-keys="expandedKeys"
        :default-checked-keys="[5]"
        :props="{ children: 'menuList', label: 'menuName' }"
        @check="handleThreeCheck"
      >
        <template #default="{ data }">
          <div class="flex items-center">
            <el-tag :type="data.type !== 2 ? 'primary' : 'info'" size="small">{{
              data.type !== 2 ? "菜单" : "权限"
            }}</el-tag>
            <span class="ml-2">{{ data.menuName }}</span>
          </div>
        </template>
      </el-tree>
    </form-drawer>
    <!-- 新增修改 -->
    <form-drawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色">
          <el-input v-model="form.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="角色描述"
            :rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            inline-prompt
            :disabled="form.isAdmin === 1"
          ></el-switch>
        </el-form-item>
      </el-form>
    </form-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useInitTable, useInitForm } from "@/hooks/useCommon";
import FormDrawer from "@/components/FormDrawer.vue";
import {
  getMenuListApi,
  getRoleListApi,
  addRoleApi,
  editRoleApi,
  deleteRoleApi,
  getCurrentRoleMenuListApi,
  setCurrentRoleMenuListApi
} from "@/api/user";

onMounted(() => {
  handleGetMenuList();
});
// 表格数据
const { tableData, currentPage, limit, total, handleDelete, handleGetTableList } = useInitTable({
  getTableList: getRoleListApi,
  deleteData: deleteRoleApi
});
// 当前角色Id
const curRoleId = ref(0);
const curRoleMenuIdList = ref([]);
// 配置权限
const treeRef = ref(null);
const { formDrawerRef: formDrawerRefRule, handleCreate: handleCreateRule } = useInitForm({});
// 配置权限-按钮
const handleConfigPermission = async (row: any) => {
  curRoleId.value = row.id;
  handleCreateRule();
  // 获取已经选中项
  const res = await getCurrentRoleMenuListApi({ category: 1, roleId: row.id });
  curRoleMenuIdList.value = (res as any).existMenuIdList;
  (treeRef.value as any).setCheckedKeys((res as any).existMenuIdList);
};

// 配置权限-提交
const handleSubmitConfigPermission = async () => {
  try {
    (formDrawerRefRule.value as any).showLoading();
    await setCurrentRoleMenuListApi({
      roleId: curRoleId.value,
      menuIdList: curRoleMenuIdList.value
    });
    (formDrawerRefRule.value as any).close();
    location.reload();
  } finally {
    (formDrawerRefRule.value as any).hideLoading();
  }
};

// 配置权限-选中
const handleThreeCheck = (e: any, node: any) => {
  const { checkedKeys, halfCheckedKeys } = node;
  curRoleMenuIdList.value = [...checkedKeys, ...halfCheckedKeys] as any;
};

// 新增或修改
const { formDrawerRef, drawerTitle, form, rules, formRef, handleSubmit, handleCreate, handleEdit } =
  useInitForm({
    form: {
      id: "",
      roleName: "",
      remark: "",
      status: 1
    },
    createData: addRoleApi,
    updateData: editRoleApi,
    success: async () => {
      handleGetTableList();
    }
  });

// 获取菜单
const handleGetMenuList = async () => {
  try {
    const res = await getMenuListApi({ category: 1 });
    curMunuList.value = res as any;
  } catch (error) {
    console.log(error);
  }
};
const curMunuList = ref([]);
// 配置权限-展开项
const expandedKeys = computed(() => {
  return curMunuList.value.map((item: any) => item.id);
});
</script>
<style scoped lang="scss"></style>
